package com.mbcn.action;

import java.util.Date;



import org.json.simple.JSONObject;

import com.mbcn.dao.MemberDAO;
import com.mbcn.dao.impl.MemberDAOImpl;
import com.mbcn.model.Member;
import com.mbcn.system.commonUtil.BaseUserAction;
import com.mbcn.system.commonUtil.Mail;
import com.mbcn.system.commonUtil.Util;

public class SigninAction extends BaseUserAction {
		
	Member member = new Member();
	MemberDAO memberDAO = new MemberDAOImpl();
	JSONObject jsonValidation = new JSONObject();
	public JSONObject getJsonValidation() {
		return jsonValidation;
	}

	public void setJsonValidation(JSONObject jsonValidation) {
		this.jsonValidation = jsonValidation;
	}

	public String doSignin() throws Exception {
		try {
			member.setJoinDate(new Date());
			member.setPassword(Util.getMD5(member.getPassword()));
			member.setMemberState((byte) 0);
			memberDAO.createMember(member);
			Mail.send(member.getEmail(),"MBCN Active Email" , "ddddd");
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		String sessionId = request.getSession().getId();
		addSessionCookie(member, sessionId);
		return SUCCESS;

	}
	
	public String doLogin() throws Exception {
		try {
			String password = Util.getMD5(member.getPassword());
			// Get session browser
			String sessionId = request.getSession().getId();
			member = Util.checkEmailExist(member.getEmail());
			if (member == null || member.getEmail() == null) {
				// Set status get email fail
				// Get error message which process in commonService
				return SUCCESS;
			}
			// In case user exist
			else {
				// Check Validate Password
				if (!password.equals(member.getPassword())) {
					// In case password incorrect
				}
				// In case password input equal password user
				else {
					// In the case email and password valid
					addSessionCookie(member, sessionId);
					}
				}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;

	}
	
	public void addSessionCookie(Member member, String sessionId) {
		// Put session userId
		session.put("memberId", member.getMemberId().intValue());
		// Put session kengenKbn
		session.put("memberRole", member.getMemberRole());
		session.put("memberAvt", member.getMemberAvt());
		session.put("memberNm", member.getMemberNm());
		// Put session browser
		session.put("sessionId", sessionId);

		// Add infor session user login
		// Put session email
		session.put("email", member.getEmail());
	}
	
	public String doLogout() {
		
		// Remove session
		session.remove("email");
		session.remove("memberId");
		session.remove("memberRole");
		session.remove("sessionId");
		session.remove("memberNm");
		session.remove("memberAvt");
	
		return SUCCESS;
	}
	
	public Object getModel() {
		return member;
	}

}
